import {
  CommandType,
  ICellData,
  ICommand,
  ICommandService,
  IUniverInstanceService,
  Inject,
  Injector,
  Plugin,
  UniverInstanceType,
  Workbook,
} from "@univerjs/core";

import {
  ComponentManager,
  IMenuService,
  MenuGroup,
  MenuItemType,
  MenuPosition,
} from "@univerjs/ui";

import { SaveSingle } from "@univerjs/icons";

/**
 * 实例化按钮插件
 */
class SaveDataButtonPlugin extends Plugin {
  static override pluginName = "save-data-plugin";
  constructor(
    _config: null,
    // inject injector, required
    @Inject(Injector) override readonly _injector: Injector,
    // inject menu service, to add toolbar button
    @Inject(IMenuService) private menuService: IMenuService,
    // inject command service, to register command handler
    @Inject(ICommandService) private readonly commandService: ICommandService,
    // inject component manager, to register icon component
    @Inject(ComponentManager)
    private readonly componentManager: ComponentManager
  ) {
    super();
  }

  /**
   * The first lifecycle of the plugin mounted on the Univer instance,
   * the Univer business instance has not been created at this time.
   * The plugin should add its own module to the dependency injection system at this lifecycle.
   * It is not recommended to initialize the internal module of the plugin outside this lifecycle.
   */
  onStarting() {
    // register icon component
    this.componentManager.register("SaveSingle", SaveSingle);

    const buttonId = "save-data-button";

    const menuItem = {
      id: buttonId,
      title: "保存数据",
      tooltip: "获取数据并保存",
      icon: "SaveSingle", // icon name
      type: MenuItemType.BUTTON,
      group: MenuGroup.CONTEXT_MENU_DATA,
      positions: [MenuPosition.TOOLBAR_START],
    };

    this.menuService.addMenuItem(menuItem, {});

    const command: ICommand = {
      type: CommandType.OPERATION,
      id: buttonId,
      handler: (accessor) => {
        // inject univer instance service
        const univer = accessor.get(IUniverInstanceService);

        // get current sheet
        const sheet = univer
          .getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!
          .getActiveSheet();
        // 保存数据
        const res = sheet.getSnapshot();
        const data = res.cellData;
        console.log("表中数据", data);
        return true;
      },
    };

    this.commandService.registerCommand(command);
  }
}

export default SaveDataButtonPlugin;
